<template>
  <div class="bg-white page-content content relative-position">
    <div class="font-16 margin-20 box">
      <div class="account-title">调用请求账号</div>
      <q-btn v-if="showCreateAccout" unelevated class="btn margin-10" style="margin: 10px 20px" label="创建账号" color="primary" @click="createClientCredentials"/>
      <div v-else class="flex">
        <div class="account-wrapper flex">
          <div class="content-title">CLIENTID</div>
          <div class="content-text">{{ clientId || '--' }}</div>
        </div>
        <div class="account-wrapper flex">
          <div class="content-title" style="border-left: 1px solid #D3D3D3">SECRET</div>
          <div class="content-text">{{ secret || '--' }}</div>
        </div>
      </div>
    </div>
    <div class="margin-r-20 margin-l-20 margin-b-20">
      <div class="title-name margin-b-20">推送参数配置</div>
      <div class="flex" v-if="showCreate">
        <yz-input
          v-model="type"
          inputType="select"
          style="width: 300px"
          class="margin-r-30"
          :options="typeOption"
          title="认证方式"
        ></yz-input>
        <q-btn unelevated class="btn margin-l-20" label="确认" color="primary" @click="createSimpleAuthentications"/>
      </div>
      <div class="font-16">
        <div class="box margin-b-20">
          <div class="account-title">订阅加密参数</div>
          <div class="secret-line account-wrapper full-width flex border-bottom">
            <div class="content-title bg-white">签名秘钥</div>
            <div class="content-text">{{ signatureKey || '--' }}</div>
          </div>
          <div class="secret-line account-wrapper full-width flex" :class="{'border-bottom' : !!token}">
            <div class="content-title">加密秘钥</div>
            <div class="content-text">{{ secretKey || '--' }}</div>
          </div>
          <div class="secret-line account-wrapper full-width flex" v-if="token">
            <div class="content-title bg-white">安全令牌</div>
            <div class="content-text">{{ token }}</div>
          </div>
        </div>
        <div>
          <div class="flex items-center">
            <div class="title-name">账号推送地址</div>
            <div class="cursor-pointer margin-l-10">
              <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" style="margin-top: -3px"/>
              <q-tooltip max-width="300px">根据推送类型对应参数推送数据至指定地址 连续推送失败5次后接口挂起。</q-tooltip>
            </div>
          </div>
          <q-btn class="margin-r-10 btn margin-t-15" outline color="primary" label="新增" @click="openAddDialog"/>
          <q-table :pagination="pagination"
                   class="myTable scroll stick-last-col margin-b-20"
                   :columns="columns"
                   :data="tableData"
                   :loading="isTableLoading"
                   style="max-height: 100%;min-height: 200px"
                   row-key="id"
                   flat
                   :hide-bottom="tableData && tableData.length !== 0"
                   no-data-label="暂无数据">
            <template v-slot:body-cell-pushType="props">
              <q-td>
                {{pushNameObj[props.row.pushType]}}
              </q-td>
            </template>
            <template v-slot:body-cell-pushUrl="props">
              <q-td>
                <div class="flex">
                  <div>{{props.row.pushUrl}}</div>
                  <div class="cursor-pointer margin-l-10" v-if="!!props.row.isFailure">
                    <q-icon name="iconfont icontubiao-113" class="font-18" style="margin-top: -3px;color: #e43434"/>
                    <q-tooltip max-width="300px">接口挂起如已修复点击重置按钮。</q-tooltip>
                  </div>
                </div>
              </q-td>
            </template>
            <template v-slot:body-cell-operations="props">
              <q-td>
                <div class="btn-group">
                  <q-btn
                    flat
                    round
                    dense
                    color="primary"
                    :disable="!props.row.isFailure"
                    class="iconfont icontongbu font-18"
                    @click="resetDataPushItem(props.row.id, props.row.pushType)"
                  >
                    <q-tooltip>重置</q-tooltip>
                  </q-btn>
                  <q-btn
                    flat
                    round
                    dense
                    color="primary"
                    class="iconfont icontubiao-12 font-18"
                    @click="updateDataPushItem(props.row)"
                  >
                    <q-tooltip>编辑</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-throttle
                    flat
                    round
                    dense
                    color="primary"
                    class="iconfont icontubiao-16 font-18"
                    @click="deleteDataPushItem(props.row.id, props.row.pushType)"
                  >
                    <q-tooltip>删除</q-tooltip>
                  </q-btn>
                </div>
              </q-td>
            </template>
          </q-table>
        </div>
      </div>
      <div class="title-name margin-b-20">邮箱设置</div>
      <div class="box flex">
        <div class="account-wrapper flex full-width">
          <div class="content-title" style="width: 50%">触发条件</div>
          <div class="content-title" style="width: 50%;border-right: none">接受角色</div>
        </div>
        <div class="account-wrapper flex full-width">
          <div class="content-text" style="width: 50%;border-right: 1px solid #D3D3D3">数据推送失败</div>
          <div class="content-text cursor-pointer" style="width: 50%;color: #5f77fd" @click="addRole">{{ selectName || '--'}}</div>
        </div>
      </div>
    </div>
    <basic-dialog :visible="show"
                  :title="isEdit ? '编辑推送信息' : '添加推送信息'"
                  max-width="500px"
                  is-show-basic-footer
                  @close="show=false"
                  @submit="submit"
    >
      <q-form ref="form" @submit="submit" class="q-gutter-md dialog-content padding-l-20 padding-r-20">
        <div style="margin-top: 40px">
          <yz-input v-model="queryParams.pushType"
                    :rules="[0]"
                    inputType="select"
                    :isDisable="isEdit"
                    :options="pushTypeOptions"
                    title="推送类型"/>
          <yz-input v-model="queryParams.pushUrl"
                    inputType="input"
                    title="推送地址"
                    :rules="[0]"
                    :hint-rule="[val => /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/.test(val) || '请输入正确地址']"
          />
        </div>
      </q-form>
    </basic-dialog>

    <RolesSelect :show="rolesShow"
                 @close="rolesShow=false"
                 :sourceData="sourceData"
                 :haveSelected="haveSelected"
                 @selectSuccess="selectRoleSuccess"/>
  </div>
</template>

<script>
import {
  bizTemplatesEmail,
  createClientCredentials, createDataPush, createSimpleAuthentications, deleteDataPush,
  getClientCredentials, getDataPush,
  getDataPushConfigs, getSimpleAuthentications, getTemplatesEmail, resetDataPush, updateDataPush
} from '../../../boot/factory/interface-config'
import RolesSelect from 'src/pages/factory/message-set/components/roles-select'
import _ from 'lodash'
import MESSAGELIST from 'src/boot/factory/msg-list'
const { getlistRoles } = MESSAGELIST

export default {
  name: 'interface-config',
  components: {
    RolesSelect
  },
  data () {
    return {
      clientId: '',
      secret: '',
      secretKey: '',
      signatureKey: '',
      token: null,
      queryParams: {
        id: '',
        pushUrl: '',
        pushType: ''
      },
      submitLoading: false,
      tableData: [],
      isEdit: false,
      show: false,
      columns: [
        { name: 'pushType', label: '推送类型', align: 'left', field: 'pushType' },
        { name: 'pushUrl', label: '推送地址', align: 'left', field: 'pushUrl' },
        { name: 'operations', label: '操作', field: 'operations', align: 'left' }
      ],
      pushTypeAllOptions: [
        { label: '生产计划完工回写', value: 1 },
        { label: '工序计划完工回写', value: 2 },
        { label: '设备状态上报', value: 3 },
        { label: '工件计数上报', value: 4 },
        { label: '实时数据上报', value: 5 },
        { label: '设备报警数据上报', value: 6 },
        { label: '刀具使用寿命数据上报', value: 7 },
        { label: '报工数据上报', value: 8 },
        { label: '工单关闭数据上报', value: 10 },
        { label: 'DNC-程序上传结果', value: 11 },
        { label: '设备倍率信息上报', value: 12 },
        { label: '阈值报警信息上报', value: 13 }
      ],
      // 使分页每页显示无限条
      pagination: {
        rowsPerPage: 0
      },
      isTableLoading: false,
      showCreate: false,
      showCreateAccout: false,
      type: 1,
      typeOption: [{
        label: '基础认证',
        value: 1
      }],
      rolesShow: false,
      sourceData: [],
      roles: [],
      editRow: null,
      msgGroups: []
    }
  },
  created () {
    this.getClientCredentials()
    this.getConfig()
    this.getRoleList()
  },
  computed: {
    haveSelected () {
      return _.cloneDeep(this.msgGroups)
    },
    selectName () {
      return this.msgGroups.map(item => item.name).join(',')
    },
    pushTypeOptions () {
      if (!this.isEdit && this.tableData && this.tableData.length > 0) {
        return this.pushTypeAllOptions.filter(item => this.tableData.findIndex(data => data.pushType === item.value) === -1)
      }
      return this.pushTypeAllOptions
    },
    pushNameObj () {
      const obj = {}
      this.pushTypeAllOptions.forEach(item => {
        obj[item.value] = item.label
      })
      return obj
    }
  },
  methods: {
    getClientCredentials () {
      getClientCredentials().then(res => {
        if (res.code === '1503') {
          this.showCreateAccout = true
        } else if (res.code === '1200') {
          this.showCreateAccout = false
          const response = res.data
          this.clientId = response.clientId
          this.secret = response.secret
        }
      })
    },
    createClientCredentials () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要创建请求推送账号吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        createClientCredentials().then(() => {
          this.getClientCredentials()
        })
      })
    },
    // 获取配置信息
    getConfig () {
      // 获取配置信息
      getDataPushConfigs().then(res => {
        // 如果不存在则创建配置
        if (!res.data) {
          this.showCreate = true
        } else {
          this.showCreate = false
          const data = res.data
          this.secretKey = data.secretKey
          this.signatureKey = data.signatureKey
          this.getDataPushItem()
          // 当tokenProcessorType为1时候，获取token信息
          if (data.tokenProcessorType === 1) {
            getSimpleAuthentications().then(res => {
              this.token = res.data
            })
          }
        }
      })
    },
    createSimpleAuthentications () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确认选择此认证方式创建吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        this.$q.loading.show()
        createSimpleAuthentications().then(r => {
          // 创建完成后，再回调获取配置信息
          this.getConfig()
        }).finally(() => {
          this.$q.loading.hide()
        })
      })
    },
    // 提交推送信息
    submit () {
      this.$refs.form.validate(true).then(result => {
        if (result) {
          const data = {
            pushUrl: this.queryParams.pushUrl,
            pushType: this.queryParams.pushType
          }
          if (this.isEdit) {
            updateDataPush(this.queryParams.id, data).then(() => {
              this.getDataPushItem()
              this.show = false
            })
          } else {
            createDataPush(data).then(() => {
              this.getDataPushItem()
              this.show = false
            })
          }
        }
      })
    },
    // 获取推送信息
    getDataPushItem () {
      this.isTableLoading = true
      getDataPush().then(res => {
        this.tableData = res.data
      }).finally(() => {
        this.isTableLoading = false
      })
    },
    // 删除推送信息
    deleteDataPushItem (id, pushType) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除此项吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        this.isTableLoading = true
        deleteDataPush(id, pushType).then(() => {
          this.$message.success('删除成功')
          this.getDataPushItem()
        })
      })
    },
    // 重置
    resetDataPushItem (id, pushType) {
      resetDataPush(id, pushType).then(() => {
        this.$message.success('重置成功')
        this.getDataPushItem()
      })
    },
    // 打开编辑推送信息
    updateDataPushItem (row) {
      this.show = true
      this.isEdit = true
      this.queryParams.pushType = row.pushType
      this.queryParams.pushUrl = row.pushUrl
      this.queryParams.id = row.id
    },
    // 打开新增推送信息
    openAddDialog () {
      this.show = true
      this.isEdit = false
      this.queryParams.pushType = ''
      this.queryParams.pushUrl = ''
    },
    // 获取接受角色
    getRoleList () {
      let member = []
      getlistRoles().then(res => {
        member = res.map(v => {
          const item = v
          item.value = v.id
          item.label = v.name
          return item
        })
        this.roles = [...member]
        this.getEmailRoles()
      })
    },
    // 打开添加角色
    addRole () {
      this.rolesShow = true
      this.sourceData = _.cloneDeep(this.roles)
    },
    // 获取email角色信息
    getEmailRoles () {
      getTemplatesEmail().then(res => {
        this.msgGroups = res.data
      })
    },
    // 更新选中的角色
    selectRoleSuccess (data) {
      const ids = data.map(item => item.id)
      bizTemplatesEmail(ids).then(() => {
        this.getEmailRoles()
        this.rolesShow = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.title-name {
  font-size: 18px;
  color: #5f77fd;
}

.myTable {
  margin-left: 0;
  margin-top: 20px;
  margin-right: 0;
}

.btn {
  padding: 0;
  min-width: 96px;
  min-height: 32px;
  height: 32px;
  line-height: 1;
  font-size: 16px;
}

.box{
  border: 1px solid #d3d3d3;
  border-radius: 6px;
}

.account-title{
  height: 46px;
  background: #F3F3F3;
  border-bottom: 1px solid #D3D3D3;
  line-height: 46px;
  padding-left: 20px;
}

.account-wrapper{
  width: 50%;
  display: flex;
  line-height: 46px;

  .content-title{
    width: 144px;
    height: 46px;
    background: #F3F3F3;
    border-right: 1px solid #D3D3D3;
    text-align: center;
  }

  .bg-white {
    background: #ffffff;
  }

  .content-text{
    padding-left: 20px;
  }
}

.border-bottom{
  border-bottom: 1px solid #d3d3d3;
}

.secret-line:nth-child(odd){
  background: #F3F3F3
}

.doc{
  position: absolute;
  bottom: 20px;
  left: 20px;
  font-size: 14px;
  font-weight: 500;
  color: #5F77FD;

  a{
    text-decoration: underline;
    color: #5F77FD
  }
}
</style>
